package com.woniuxy.threadmethods;

import com.woniuxy.untis.Sleep;
import lombok.extern.slf4j.Slf4j;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 等待对方返回结果
 * <P> Date: 2022/4/7:15:11
 * <P> Description:
 */
@Slf4j(topic = "c.Test20")
public class Test20 {

    public static void main(String[] args) {
        GuardedObject guardedObject = new GuardedObject();

        //TODO 线程1 等待线程2的结果
        Thread t1 = new Thread(() -> {
            log.debug("等待结果");
            log.debug("结果：{}", guardedObject.get(1000));
        }, "t1");
        t1.start();

        Thread t2 = new Thread(() -> {
            log.debug("执行下载");
            Sleep.sleep(2000);

            guardedObject.complete(new Object());
        }, "t2");

        t2.start();


    }
}



class GuardedObject {

    /**
     * TODO 结果
     */
    private Object response;


    /**
     * TODO: 提取结果
     **/
    public Object get(long outTime) {
        synchronized (this) {
            //记录开始时间
            long begin = System.currentTimeMillis();

            //记录经历的时间
            long passedTime = 0;

            while (response == null) {

                long waitTime = outTime - passedTime;
                //如果经历时间超过最大等待时间
                if (waitTime <= 0) {
                    break;
                }
                try {
                    //TODO 虚假唤醒 限定他的超时 获得接下来还需要等待的时间

                    this.wait(waitTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                passedTime = System.currentTimeMillis() - begin;
            }
            return response;
        }
    }

    /**
     * TODO:产生结果
     **/
    public void complete(Object response) {
        synchronized (this) {
            this.response = response;
            this.notifyAll();
        }
    }

}
